package com.sz.app.edi.job.sms;

import com.aliyuncs.exceptions.ClientException;
import com.sz.common.base.job.JobScheduler;
import com.sz.common.base.logger.Logger;
import com.sz.common.base.utils.JsonUtils;
import com.sz.common.core.service.sms.SmsService;
import com.sz.common.core.system.dto.SmsBodyDto;
import com.sz.common.core.system.entity.SysSMS;
import com.sz.common.core.system.service.SysSmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

/**
 * Function: TODO: ADD FUNCTION <br>
 * Author: Johnboy <br>
 * Date: 2017-08-15 15:48:00
 */
@Service("sendSMSJobScheduler")
public class SendSmSJobSchedulerImpl implements JobScheduler {
    public static final String OK = "ok";
    public static final String ISV_ACCOUNT_ABNORMAL = "isv.ACCOUNT_ABNORMAL";
    public static final String ISP_SYSTEM_ERROR = "isp.SYSTEM_ERROR";
    @Autowired
    private SmsService smsService;

    @Autowired
    private SysSmsService sysSmsService;

    Logger logger = Logger.getLogger(this.getClass());

    @Override
    public void execute() throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();
        logger.info("==============start sendSMSJobScheduler");
        List<SysSMS> sysSMSList = sysSmsService.getAllNeddSendSMS();
        if (sysSMSList != null && sysSMSList.size() > 0) {
            for (SysSMS sysSMS : sysSMSList) {
                logger.info("", sysSMS);
                sendSMS(sysSMS);
            }
        }
        long end = System.currentTimeMillis();
        logger.info("==============end sendSMSJobScheduler,use time:" + (end - start) + "ms");
    }

    private void sendSMS(SysSMS sysSMS) {
        String body = sysSMS.getBody();
        SmsBodyDto smsBodyDto = new SmsBodyDto();
        try {
            List<String> keys = new ArrayList<>();
            List<String> values = new ArrayList<>();
            Map<String, String> smsBody = JsonUtils.toObject(body, Map.class);
            smsBody.forEach((key, value) -> {
                keys.add(key);
                values.add(value);
            });
            smsBodyDto.setSmsTemplateValue(values);
            smsBodyDto.setSmsTemplateKey(keys);
        } catch (Exception e) {
            sysSmsService.setSmsFailStatus(sysSMS.getId(), "数据异常");
        }
        try {
            String code = smsService.send(sysSMS.getPhone(), sysSMS.getTemplateCode(), smsBodyDto);
            if (OK.equalsIgnoreCase(code)) {
                sysSmsService.updateSendResult(sysSMS.getId(), true, null);
                logger.info("send SMS success" + code);
            }
            else if (ISV_ACCOUNT_ABNORMAL.equalsIgnoreCase(code) || ISP_SYSTEM_ERROR.equalsIgnoreCase(code)) {
                //系统错误
                logger.error("SMS发送错误,error code : " + code);
                sysSmsService.updateSendResult(sysSMS.getId(), false, code);
            }
            else {
                logger.error("SMS发送错误,error code : " + code);
                sysSmsService.setSmsFailStatus(sysSMS.getId(), code);
            }
        } catch (ClientException e) {
            logger.error("SMS发送错误", e);
            sysSmsService.updateSendResult(sysSMS.getId(), false, e.getErrMsg());
        }
    }
}
